package com.huisang.springboot.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.huisang.springboot.entity.FileA;
import com.huisang.springboot.mapper.FileMapper;
import com.huisang.springboot.service.FileService;
import com.huisang.springboot.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 文件上传相关接口
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${files.upload.path}")
    private String fileUploadPath;
    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private FileService fileService;

    private FileA getFileMd5(String md5) {

        QueryWrapper<FileA> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("md5", md5);
        List<FileA> list = fileMapper.selectList(queryWrapper);
        return list.size() > 0 ? list.get(0) : null;
    }

    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        long size = file.getSize();
    //先存储到磁盘

        //定义文件唯一标识码
        String uuid = IdUtil.fastSimpleUUID();
        String uuFile = uuid + StrUtil.DOT + type;

        File uploadFile = new File(fileUploadPath + uuFile);

        //判断上传目录是否存在，不存在则创建目录
        if(!uploadFile.getParentFile().exists()) {
            uploadFile.getParentFile().mkdir();
        }
    //数据库查询重复文件
        //把获取到的文件存储到磁盘目录去
        file.transferTo(uploadFile);
        //MD5检测重复文件
        String md5 = SecureUtil.md5(uploadFile);
        //通过md5查询文件
        FileA one = getFileMd5(md5);

        String url = null;
        if(one != null) {
            url = one.getUrl();
            //删除
            uploadFile.delete();
        }else {//查不到文件，上传文件
            url = "http://localhost:8081/file/" + uuFile;

        }
                //存储数据库
        FileA fileA1 = new FileA();
        fileA1.setName(originalFilename);
        fileA1.setType(type);
        fileA1.setSize(size / 1024);
        fileA1.setUrl(url);
        fileA1.setEnable(true);
        fileA1.setIsDelete(false);
        fileA1.setMd5(md5);
        fileMapper.insert(fileA1);
        return url;
    }

    @PutMapping
    public Result<Boolean> updateFile(@RequestBody FileA file) {
        return fileService.updateFile(file);
    }

    @GetMapping("/{uuFile}")
    public void downLoad(@PathVariable String uuFile, HttpServletResponse response) throws IOException {
        File downLoadFile = new File(fileUploadPath + uuFile);
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(uuFile, "UTF-8"));
        response.setContentType("application/octet-stream");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(FileUtil.readBytes(downLoadFile));
        outputStream.flush();
        outputStream.close();
    }

    //分页查询，mybatis-plus
    @GetMapping("/page")
    public Result<IPage<FileA>> getUserPageList(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam(required = false) String name) {
        return fileService.getFilePageList(pageNum, pageSize, name);
    }

    @DeleteMapping("/{id}")
    public Result<Boolean> deleteFile(@PathVariable Integer id){
        return fileService.deleteFile(id);
    }

    @PostMapping("/batch")
    public Result<Boolean> deleteBatchFile(@RequestBody List<Integer> ids){
        return fileService.deleteBatchFile(ids);
    }


}
